package com.example.hystrixconsumer.controller;


import com.example.hystrixconsumer.domain.Goods;
import com.example.hystrixconsumer.service.GoodsService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * Goods Controller 服务提供方
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;

    /**
     * 降级：
     *  1.出现异常
     *  2.服务调用超时
     *      默认1s超时
     *     @HystrixCommand(fallbackMethod = "findOne_fallback")
     *     fallbackMethod:指定降级方法
     *     circuitBreaker.sleepWindowInMilliseconds：监控时间 默认5000 毫秒
     *     circuitBreaker.requestVolumeThreshold：失败次数。默认20次
     *     circuitBreaker.errorThresholdPercentage：失败率 默认50%
     * @param id
     * @return
     */
    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOne_fallback",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000"),
//            --------熔断阈值设置（默认为5s，请求失败20次）--------
            //监控时间 默认5000 毫秒
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "5000"),
            //失败次数。默认20次
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "20"),
            //失败率 默认50%
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50")
            })//设置超时时间为3s
    public Goods findOne(@PathVariable("id") int id){
//      1.造个异常
//        int m = 1 / 0;
        // 2.超时时间
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("暂停2s");
        }
        Goods goods = goodsService.findOne(id);

        goods.setTitle(goods.getTitle() + ":" + port);//将端口号，设置到了 商品标题上
        return goods;
    }

    /**
     * 定义降级方法
     * 1.方法的返回值需要和原方法一样
     * 2.方法的参数需要和原方法意义
     */
    public Goods findOne_fallback(int id) {
        Goods goods = new Goods();
        goods.setTitle("方法降级了");
        return goods;
    }
}
